import sys
import os
import md5
import traceback
import imp
import datetime
import sqlite3

def load_module(code_path):
    try:
        try:
            code_dir = os.path.dirname(code_path)
            code_file = os.path.basename(code_path)

            fin = open(code_path, 'rb')

            return  imp.load_source(md5.new(code_path).hexdigest(), code_path, fin)
        finally:
            try: fin.close()
            except: pass
    except ImportError, x:
        print sys.path
        traceback.print_exc(file = sys.stderr)
        raise
    except:
        print sys.path
        traceback.print_exc(file = sys.stderr)
        raise

def bool_to_int(val):
    if val:
        return 1
    return 0

if __name__ == "__main__":
    print "Installing plugin..."
    file_name = sys.argv[1]
    full_file_path = os.path.abspath(file_name)
    config = load_module(full_file_path)

    install_date = str(datetime.datetime.now())
    auto_start = bool_to_int(config.AUTO_START)
    run_once = bool_to_int(config.RUN_ONCE)
    run_count = 0
    state = "stopped"

    print "Installing with Parameters...."    
    print "NAME:",config.NAME
    print "PARENT:",config.PARENT
    print "INSTALL_DATE:",install_date
    print "AUTO_START:",auto_start
    print "RUN_ONCE:",run_once
    print "RUN_COUNT:",run_count
    print "STATE:",state
    print "SEQUENCE:",config.SEQUENCE

    values = (config.NAME, config.PARENT, install_date, auto_start, run_once, run_count, config.SEQUENCE, state)

    cc = sqlite3.connect(os.path.expanduser(os.path.join("~","db","plugins.db")))
    c = cc.cursor()
    c.execute("replace into plugins values(?,?,?,?,?,?,?,?)",values)
    cc.commit()

